// 导出页面为PDF格式
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
var imgarr = []
let PDF = new JsPDF('', 'pt', ['283.46' , '320.315'])
PDF.setFont('helvetica', 'normal');
PDF.setTextColor(0, 0, 0);
 function  addPadf( id , length){
  return new Promise((resolve,reject)=>{
     for(var i=0 ; i<length ; i++ ){
      var newid = id+i
      html2Canvas(document.querySelector(newid), {
        allowTaint: true
      }).then(canvas=>{
         let pageData = canvas.toDataURL('image/jpeg')
        imgarr.push({base64:pageData})
        console.log(i , length)

        if(imgarr.length == length){
          console.log()
            resolve(imgarr)
        }
      })
    }

  })
}
// 将base64转换为文件对象

function dataURLtoFile (dataurl, filename ) {
  let arr = dataurl.split(',')
  let mime = arr[0].match(/:(.*?);/)[1]
  let bstr = atob(arr[1])
  let n = bstr.length
  let u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  // 转换成file对象
  return new File([u8arr], filename, { type: mime })
  // 转换成成blob对象
  // return new Blob([u8arr],{type:mime})
}

export default function getPdf(id,title,length,isDown=false){
  addPadf(id , length).then(res=>{
    // PDF.save('面单' + '.pdf')
    PDF = new JsPDF('', 'pt', ['283.46' , '320.315'])
    imgarr = []

    res.forEach((item,index)=>{
      console.log(item , '返回')
      if(index!=0){
        PDF.addPage()
      }
      PDF.addImage(item.base64, 'JPEG', 0, 0, 283.46, 320.315)
    })
        if(isDown){
          PDF.save(title + '.pdf')
        }
        // 将pdf输入为base格式的字符串
        let buffer = PDF.output('datauristring')
        // 将base64格式的字符串转换为file文件
        let myfile = dataURLtoFile(buffer, title + '.pdf')
        let blob = PDF.output('blob')
        let pdfUrl = window.URL.createObjectURL(blob);
        console.log(pdfUrl)
        //使用 window.open 打开即可
         window.open(pdfUrl);
  })
}
